﻿/*
    Project: IV:MP GUI Editor (http://code.google.com/p/ivmp-gui-editor)
    Code license: GNU Lesser GPL (http://www.gnu.org/copyleft/lesser.html) 
 */

using System;
using System.IO;
using System.Text;
using System.Threading;
namespace IvmpEditor
{
    public interface ICompiler
    {
        bool IsCompileDone { get; }
        string InfoText { get; }
        void Compile(string sourceFileName, Encoding sourceEncoding);
        void RequestAbort();
        bool IsCompileAborted { get; }

        event _Compiler.SendString SetStatus;
        event _Compiler.SendString FatalError;
        event _Compiler.Signal CompilationStarted;
        event _Compiler.Signal CompilationFinished;
    }
    public static class _Compiler
    {
        public delegate void SendString(ICompiler sender, string text);
        public delegate void Signal(ICompiler sender);

        public static bool WaitForProcessExit(ref bool kill, System.Diagnostics.Process proc)
        {
            // Waiting for process exit, regulary checking kill(abort) flag.
            while(!proc.HasExited)
            {
                if (kill)
                {
                    // If abort requested, killing process and returning false.
                    proc.Kill();
                    return false;
                }

                proc.WaitForExit(1000);
            }

            // Process exited gracefuly
            return true;
        }
        public static void HoldCompilerLock(LockFile lockFile, ref bool abort)
        {
            // Holding lock file, if failed, throwing exception
            if (!lockFile.TryHold())
            {
                var lockResult = lockFile.TryHold(20 * 1000, ref abort);
                if (lockResult == LockFile.TimedHoldkResult.Failed)
                    throw new ApplicationException("Locking failed, this means you have another instance running.");
                else if (lockResult == LockFile.TimedHoldkResult.Aborted)
                    throw new ThreadStateException();
            }
        }
    }
}
